<?php
namespace plugin\ky_shouyin\app\controller\admin;

use plugin\admin\app\model\Option;
use support\Request;
use support\Db;
use plugin\ky_shouyin\app\controller\BaseController;
use Webman\Http\Response;

class IndexController extends \plugin\ky_shouyin\app\controller\admin\BaseController
{
    /**
     * 后台首页
     */
    public function index()
    {
        $auth = $this->beforeAction();
        if ($auth instanceof Response) {
            return $auth;
        }

        // 获取今天的开始和结束时间
        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');
        
        // 今日新增会员数
        $today_new_members = Db::table('ky_member')
            ->whereBetween('created_at', [$today_start, $today_end])
            ->count();
            
        // 今日会员充值金额
        $today_recharge = Db::table('ky_member_recharge')
            ->whereBetween('created_at', [$today_start, $today_end])
            ->sum('amount');
            
        // 今日营业额（订单实付金额）
        $today_sales = Db::table('ky_order')
            ->where('status', 1) // 已支付的订单
            ->whereBetween('created_at', [$today_start, $today_end])
            ->sum('paid_amount');
            
        // 累计会员数
        $total_members = Db::table('ky_member')
            ->where('ky_member.status', '<>', 3)
            ->count();
        
        // 累计交易额
        $total_sales = Db::table('ky_order')
            ->where('status', 1)
            ->sum('paid_amount');
            
        // 商品总数
        $total_goods = Db::table('ky_goods')
            ->where('status', 1)
            ->count();
            
        $data = [
            'today_new_members' => $today_new_members,
            'today_recharge' => $today_recharge ?: 0,
            'today_sales' => $today_sales ?: 0,
            'total_members' => $total_members,
            'total_sales' => $total_sales ?: 0,
            'total_goods' => $total_goods
        ];
        
        $admin = session('user.id') ?? session('user.uid');
        if (!$admin) {
            $name = 'system_config';
            $config = Option::where('name', $name)->value('value');
            $config = json_decode($config, true);
            $title = $config['logo']['title'] ?? 'webman admin';
            $logo = $config['logo']['image'] ?? '/app/admin/admin/images/logo.png';
            return raw_view('admin/account/login',['logo'=>$logo,'title'=>$title]);
        }
        return $this->view('admin/index', $data);
    }
} 